const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.connect('mongodb://localhost:27017/experiencemanager', { useNewUrlParser: true, useUnifiedTopology: true });
const ExpSchema = new Schema({
    expId:{type:Number},
    userAccount: { type: Number},//有默认值的属性在插入时不添加数据会自动以默认值插入
    originalTitle:{type:String},
    originalContent:{type:String},
    title:{type:String},
    content: { details: { type: String }, date: { type: Date, default: Date.now } },//对插入这个对象的每一项对象数据的约束条件
    browseNum:{type:Number,default:0},
});

const Exp = mongoose.model('Exp', ExpSchema);


//发布文章方法
exports.releaseExp = function (expinfo, callback) {
    function search(){
        let random=Math.round(Math.random()*10000000000)
        Exp.find({
            expId:random
        }, function (err, res) {
            if (err) {
                callback({info:"发布失败"})
            }
            else {
                if (res.length == 0) {
                    const exp = new Exp({

                        expId:random,
                        originalTitle:expinfo.originalTitle,
                        originalContent:expinfo.originalContent,
                        userAccount:expinfo.userAccount,
                        title:expinfo.title,
                        content:{details:expinfo.content}

                    })
                    exp.save().then(() => {
                        callback({info:{
                                expId:random,
                                userAccount:expinfo.userAccount,
                                title:expinfo.title,
                                content:expinfo.content,
                                originalTitle:expinfo.originalTitle,
                                originalContent:expinfo.originalContent,
                            }})
                    });
                }
                else {
                    search()
                }
            }
        })
    }
    search()
}

//前十条热门文章
exports.hotsearch=function (callback) {
    Exp.find().limit(8) // 最多显示10条
        .sort({'browseNum': -1}) // 倒序
        .exec(function (err, doc) { // 回调
            if (err) {
                callback({info:"404",err})
            } else {

                callback({code: "ok", data: doc, count:doc.length})
            }
        })
}



//根据用户的关键字模糊查询经验数据

exports.ProbablyExp=function (keyword,callback) {
    // 设置查询条件
    let index=0;
    var reg = new RegExp("[,，。. ]","gi");
    let newkeyword = keyword.replace(reg,"");
    console.log("keyword"+keyword)
   async function findResult(keyword){


       var _filter={
           $or: [  // 多字段同时匹配
               {"title": {$regex: keyword,$options:'i'}},//添加$options:'i'属性在匹配时不区分大小写
               {"content.details": {$regex: keyword,$options:'si'}  }
           ]
       }
       var count = 0
       Exp.count(_filter, function (err, doc) { // 查询总条数（用于分页）
           if (err) {
               console.log(err)
           } else {
               count = doc
           }
       })

     var list= await new Promise((resolve,reject)=>{
            Exp.find(_filter).limit(30) // 最多显示30条
                .sort({'browseNum': -1}) // 倒序
                .exec(function (err, doc) { // 回调
                    if (err) {
                        callback({info:"404",err})
                    } else {
                        resolve(doc)

                    }
                })
        })
       if(newkeyword.length<5){
           callback({info:"搜索成功",data:list})
       }
       else{
           if(list.length==0){
               if(index>=newkeyword.length/2){
                   callback({info:"搜索成功",data:list})
               }
               else{
                   index+=1;
                   keyword= newkeyword.substr(index+1,2);
                   console.log(keyword)
                   findResult(keyword)
               }
           }
           else{
               callback({info:"搜索成功",data:list})
           }
       }
    }
    findResult(newkeyword);

}

//根据经验id查询经验详情信息
exports.currentExperience=function (expId,callback) {
    let browseNum=0
    Exp.find({
        expId,
    }, function (err, res) {
        if(err){
            callback(err)
        }
        else {
            browseNum= res[0].browseNum+1;
            Exp.update({expId},{browseNum},function (err,ret) {

            })
            callback({info:"查找成功",res})
        }
    })
}

//根据用户id查询该用户发布的所有经验信息
exports.currentUserExperience=function (userAccount,callback) {
    Exp.find({
        userAccount,
    }, function (err, res) {
        if(err){
            callback(err)
        }
        else {
            callback({info:"查找成功",res})
        }
    })
}